angular.module("dashboardApp")
.controller('lsComposeCtrl', [
	'$scope', '$http', '$location', 
	'$routeParams', '$timeout', '$q', 
	'editor', 'BASE_URL', 'videos', 'maps', 'questions', 'events', 'reference',
function($scope, $http, $location, $routeParams, $timeout, $q, editor, BASE_URL, videos, maps, questions, events, reference)
{

	$scope.categories = [];
	$scope.pageTitle = "";
	$scope.lsTitle = "";
	$scope.lsContent = "";
	$scope.viewIndex = false;
	$scope.paragraph = null;

	$scope.videoList = [];
	$scope.placeList = [];
	$scope.personList = [];
	$scope.articleList = [];
	$scope.mapList = [];

	$scope.questionList = [];
	$scope.dbQuestionList = [];
	questionList = [];

	$scope.eventList = [];
	$scope.dbEventList = [];
	eventList = [];

	$scope.timelineList = [];

	$scope.psListCat = [];

	$scope.popup = {};
	$scope.addVideoForm = {
		"cat": "",
		"_id": "",
		"description": ""
	}
	$scope.addQuestionForm = {
		"cat": "",
		"question": "",
		"answer": ""
	}

	$scope.searchRefer = '';
	var popupMap = null;

	// Initialize Compose Section
	var lsId = $routeParams.lsId;
	$scope.typeCompose = $routeParams.type;
	$scope.$watch('typeCompose', function(val) {
		console.log(val);
	})

	if(lsId == 'untiled') {
		switch($scope.typeCompose) {
			case 'lesson': $scope.pageTitle = "TẠO BÀI VIẾT MỚI";
				break;
			case 'place': $scope.pageTitle = "TẠO BÀI VIẾT VỀ DI TÍCH LỊCH SỬ";
				break;
			case 'person': $scope.pageTitle = "TẠO BÀI VIẾT VỀ CON NGƯỜI LỊCH SỬ";
				break;
		}

		$scope.create = true;
		$scope.refRegion = 'vn';
		$timeout(function() {
			$scope.$parent.loadingView = false;
		},1000)
		.then(
			$timeout(function() {

				// Construct Editor
				$('#redactor-content').redactor({
					focus: true,
					plugins: ['table','fontsize','fontcolor','advandce']
				});
				editor.renderNew();
			}, 500)
		)
	}
	else {
		switch($scope.typeCompose) {
			case 'lesson': $scope.pageTitle = "CHỈNH SỬA BÀI VIẾT MỚI";
				break;
			case 'place': $scope.pageTitle = "CHỈNH SỬA BÀI VIẾT VỀ DI TÍCH LỊCH SỬ";
				break;
			case 'person': $scope.pageTitle = "CHỈNH SỬA BÀI VIẾT VỀ CON NGƯỜI LỊCH SỬ";
				break;
		}
		// $scope.pageTitle = "CHỈNH SỬA BÀI VIẾT";	
		$scope.create = false;
		var lsData = null;

		if($scope.typeCompose == 'lesson')
			lsData = editor.getLesson(lsId);
		else if($scope.typeCompose == 'place')
			lsData = editor.getRefPlace(lsId);
		else if($scope.typeCompose == 'person')
			lsData = editor.getRefPerson(lsId);

		if(lsData) {
			lsData.then(function(data) {
				console.log(data);
				if(data == "null") {
					switch($scope.typeCompose) {
						case 'lesson': $location.path('/lscompose');
						break;
						case 'place': $location.path('/lscompose/place');
						break;
						case 'person': $location.path('/lscompose/person');
						break;
					}
					// $location.path('/lscompose');
				}
				$scope.lsTitle = data.title;
				$scope.lsContent = data.content;
				$scope.timelineList = data.timeline;

				$scope.refRegion = data.region;
				$scope.refImage = data.image;

				$scope.psDate = {
					born: data.born,
					dead: data.dead
				}
				$scope.plLocal = data.position;

				if($scope.typeCompose == 'person') {
					angular.forEach(data.category, function(cat) {
						$scope.psListCat.push({
							id: cat,
							name: '__'
						})
					})
				}

				if(data.cat && data.cat.slice(-2) == 'vn') {
					$scope.isVn = true;
				}
				$timeout(function() {
					$scope.category = data.cat;
				}, 100);

				return {
					qs: questions.getQuestions(data.questions),
					ev: events.getEvents(data.events)
				}
			}).then(function(actions) 
			{
				if(actions.qs) actions.qs.then(function(dt) {
					if(dt) {
						$scope.questionList = dt;
						for(i in dt) {
							questionList.push(dt[i]._id);
						}
					}
				});
				if(actions.ev) actions.ev.then(function(dt) {
					if(dt) {
						$scope.eventList = dt;
						for(i in dt) {
							eventList.push(dt[i]._id.$id);
						}
					}
				});

				// Construct Editor
				$('#redactor-content').redactor({
					focus: true,
					plugins: ['table','fontsize','fontcolor','advandce']
				});
			});
		}
	}	

	// Initialize Category
	editor.getCategories().then(function(dt) {
		parentArr = [];
		childArr = [];
		angular.forEach(dt, function(cat) {
			if(!cat.parent) parentArr.push(cat);
			else {
				cat.name = ' -- ' + cat.name;
				childArr.push(cat);
			}
		});		
		angular.forEach(parentArr, function(par) {
			$scope.categories.push(par);
			angular.forEach(childArr, function(child) {
				if(child.parent == par._id) {
					$scope.categories.push(child);
				}
			});
		});

		angular.forEach($scope.psListCat, function(cat) {
			for(i in $scope.categories) {
				if(cat.id == $scope.categories[i]._id) {
					cat.name = $scope.categories[i].name;
					console.log($scope.categories[i].name);
					break;
				}
			}
		})
	});

	// Initialize Video List
	editor.sliderList('#videos-list');
	videos.getVideoList().then(function(dt) {
		for(el in dt) {
			$scope.videoList.push(dt[el]);
		}
		$timeout(function() {
			$scope.$parent.loadingView = false;
		},1000).then(function() {
			$timeout(function() {
				$('.youtube-popup').magnificPopup({type: "iframe"});
			}, 200);
		});	
	});

	// Initialize Reference List
	// editor.sliderList('.reference-list');
	editor.sliderList('.place-z .reference-list');
	editor.sliderList('.person-z .reference-list');
	editor.sliderList('.article-z .reference-list');
	reference.getReferList().then(function(dt) {
		for(el in dt) {
			if(dt[el].type=='place') $scope.placeList.push(dt[el]);
			if(dt[el].type=='person') $scope.personList.push(dt[el]);
		}	
	});
	reference.getArticleList().then(function(dt) {
		for(el in dt) {
			$scope.articleList.push(dt[el]);
		}	
	});

	// Initialize Db Question List
	editor.sliderList('#pu-questions-list');
	questions.getQuestionList().then(function(dt) {
		$scope.dbQuestionList = dt;
	});

	// Initialize Events Timeline List
	events.getEventList().then(function(dt) {
		$scope.dbEventList = dt;
	})

	// Init Maps popup
	maps.initialzeMap();

	// Initialize Maps List and Timeline Maps List
	editor.sliderList('#maps-list');
	editor.sliderList('#timeline-maps-list');
	maps.getMapList().then(function(dt) {
		for(el in dt) {
			$scope.mapList.push(dt[el]);  // Map List use for both list
			// $scope.timelineMapList.push(dt[el]);
		}
	// 	console.log($scope.mapList);
	});


	$scope.$watch('lsContent', function(newVal, oldVal) {
		$('.redactor-editor').html(newVal);
		$('#redactor-content').val(newVal);
	});
	$scope.$watch('isVn', function(newVal, oldVal) {
		if(newVal != oldVal) {
			$scope.addVideoForm.cat = "";
			$scope.category = "";
		}
	});

	$scope.$watch('searchVideo', function() {
		$timeout(function() {
			$("#videos-list").sly('reload');
		}, 200);
	});	
	$scope.$watch('searchRefer', function() {
		$timeout(function() {
			$(".reference-list").sly('reload');
		}, 200);
	});
	$scope.$watch('searchMap', function() {
		$timeout(function() {
			$("#maps-list").sly('reload');
			$("#timeline-maps-list").sly('reload');
		}, 200);
	});
	$scope.$watch('searchQuestion.question', function() {
		$timeout(function() {
			$("#pu-questions-list").sly('reload');
		}, 200);
	});
	$scope.$watch('viewIndex', function(newVal, oldVal) {
		$timeout(function() {
			if(!newVal) {
				$('.redactor-editor span.index').remove();
				$('.redactor-editor').attr('contenteditable', true);
			}
			else {
				$('.redactor-editor p, .redactor-editor table, .redactor-editor ul, .redactor-editor ol').each(function() {
					$(this).append('<span class="index">'+ $(this).index() +'</span>')
				});
				$('.redactor-editor').attr('contenteditable', false);
			}
		}, 200);
	});

	// =========================================================
	// =========================================================

	// Initialize Editor [Important] =====================================================
	// ===================================================================================
	// $('#redactor-content').redactor({
	// 	focus: true,
	// 	plugins: ['table','fontsize','fontcolor','advandce']
	// });

	if (!RedactorPlugins) var RedactorPlugins = {}; 
	RedactorPlugins.advanced = function()
	{
	    return {
	        init: function()
	        {
	            var button = this.button.add('advanced', 'Advanced');
	 
	            // make your added button as Font Awesome's icon
	            this.button.setAwesome('advanced', 'fa-tasks');
	 
	            this.button.addCallback(button, this.advanced.testButton);
	        },
	        testButton: function(buttonName)
	        {
	            alert(buttonName);
	        }
	    };
	};
	// ===================================================================================

	// Reload slider after popup shown.
	$('#importVideo').on('shown.bs.modal', function(e) {
		$("#videos-list").sly('reload');
	});
	$('#importReference').on('shown.bs.modal', function(e) {
		$(".reference-list").sly('reload');
	});
	$('#importMap').on('shown.bs.modal', function(e) {
		$("#maps-list").sly('reload');
	});
	$('#importQuestion').on('shown.bs.modal', function(e) {
		$("#pu-questions-list").sly('reload');
	});
	$('#addTimeline').on('shown.bs.modal', function(e) {
		$("#timeline-maps-list").sly('reload');
	});

	// Add video id to input field
	$('#videos-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#videos-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		$scope.$apply(function() {
			$scope.popup.videoId = str;
		});

	});
	// Add reference id to input field
	$('#places-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#places-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		strName = $(li).find('.name').html();
		$scope.$apply(function() {
			$scope.popup.referId = str;
			$scope.popup.referName = strName;
		});
	});
	$('#person-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#person-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		strName = $(li).find('.name').html();
		$scope.$apply(function() {
			$scope.popup.referId = str;
			$scope.popup.referName = strName;
		});
	});
	$('#article-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#article-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		strName = $(li).find('.name').html();
		$scope.$apply(function() {
			$scope.popup.referId = str;
			$scope.popup.referName = strName;
		});
	});

	// Add question id to input field
	$('#pu-questions-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#pu-questions-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		$scope.$apply(function() {
			$scope.popup.questionId = str;
		});
	});

	// Get map from slider
	$('#maps-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#maps-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		$scope.$apply(function() {
			$scope.popup.mapId = str;
		});
		maps.setPopupMap(str, 0);
	});
	$('#timeline-maps-list').sly('on','active', function() {
		pos = this.rel['activeItem'];
		li = $("#maps-list .slidee li").get(pos);
		str = $(li).find('.id').html();
		$scope.$apply(function() {
			$scope.popup.timelineMap = str;
		});
		maps.setPopupMap(str, 1);
	});

	// $('div[contenteditable]').keydown(function(e) {
	// 	if (e.keyCode === 13) {
	// 		$("#redactor-content").redactor('selection.save');
	// 	}
	// 	else $("#redactor-content").redactor('selection.restore');
	// });
	$('.import-elements').mouseenter(function() {
		$("#redactor-content").redactor('selection.save');
	})
	
	// =========================================================
	// =========================================================
	$scope.testCursor = function() {
		$('#redactor-content').redactor('caret.setOffset', 20);
	}
	$scope.saveSelection = function() {
		$('#redactor-content').redactor('selection.save');
	}
	$scope.importImage = function() {
		if($scope.imgUrl != "" && $scope.imgDescription != "")
		{
			editor.isImage($scope.imgUrl).then(function(prm) {
				if(!prm) {
					alert('Đường dẫn hình ảnh không tồn tại');
					return null;
				}
				editor.importImg($scope.imgUrl, $scope.imgDescription);
			});
		}		
	}
	$scope.importVideo = function(videoId) {
		editor.importVideo(videoId, $scope.paragraph);
	}
	$scope.importReference = function(referId, referName) {
		editor.importReference(referId, referName, $scope.paragraph);
	}
	$scope.importQuestion = function(questionId) {
		angular.forEach($scope.dbQuestionList, function(q) {
			if(q._id == questionId) {
				$scope.questionList.push(q);
				questionList.push(q._id);
			}
		})
	}	
	$scope.importEvent = function(eventId) {
		angular.forEach($scope.dbEventList, function(e) {
			if(e._id.$id == eventId) {
				$scope.eventList.push(e);
				eventList.push(e._id.$id);
			}
		})
	}
	$scope.importMap = function(mapId) {
		editor.importMap(mapId, $scope.paragraph);
	}
	$scope.addVideo = function() {
		editor.addVideo($scope.addVideoForm).then(function(dt) {
			if(dt) {
				$scope.videoList = [];
				for(el in dt) {
					$scope.videoList.push(dt[el]);
				}
				$('#addVideo').modal('hide');
				$timeout(function() {
					$("#videos-list").sly('reload');
				}, 500);
			}
		})
	}
	$scope.addQuestion = function() {
		editor.addQuestion($scope.addQuestionForm).then(function(dt) {
			if(dt) {
				$scope.dbQuestionList = [];
				for(el in dt) {
					$scope.dbQuestionList.push(dt[el]);
				}
				$('#addQuestion').modal('hide');
				$timeout(function() {
					$("#pu-questions-list").sly('reload');
				}, 500);
			}
		})
	}
	$scope.addPsCats = function() {
		cat = $scope.category;
		catName = $('#select-cat option[value='+ cat +'').text();
		if(cat == "") return null;
		override = false
		angular.forEach($scope.psListCat, function(c) {
			if(cat == c.id) {
				override = true;
				return;
			}
		})
		if(override) return;
		$scope.psListCat.push({
			id: cat,
			name: catName
		});
		// alert($scope.category);
	}
	$scope.addTimeNode = function() {
		node = {};
		node.time = $scope.strTimeNode;
		pL = [];
		angular.forEach($scope.paragraphList.split(','), function(p) {
			p = parseInt(p);
			pL.push(p);
		})
		node.paragraph = pL;
		node.maps = $scope.popup.timelineMap;
		$scope.timelineList.push(node);
	}
	$scope.deleteTlNode = function(idx) {
		$scope.timelineList.splice(idx, 1);
	}
	$scope.deleteQuestion = function(idx) {
		$scope.questionList.splice(idx, 1);
		questionList.splice(idx, 1);
	}
	$scope.deleteEvent = function(idx) {
		$scope.eventList.splice(idx, 1);
		eventList.splice(idx, 1);
	}
	$scope.addArticle = function() {
		
		data = {
			"title": $scope.lsTitle,
			"content": $('#redactor-content').val()
		}
		data.content = editor.editMapContent(data.content);
		data.content = editor.indexParagraph(data.content);

		switch($scope.typeCompose) {
			case 'lesson':
				data.cat = $scope.category;
				data.questions = questionList;
				data.events = eventList;
				data.timeline = $scope.timelineList;

				editor.addArticle(data);
				break;
			case 'person':
				cats = [];
				for(i in $scope.psListCat) {
					cats.push($scope.psListCat[i].id);
				}
				data.type = 'person';
				data.category = cats;
				data.image = $scope.refImage;
				data.born = $scope.psDate.born;
				data.dead = $scope.psDate.dead;
				data.region = $scope.refRegion;

				editor.addReference(data);
				break;
			case 'place':
				data.type = 'place';
				data.image = $scope.refImage;
				data.position = $scope.plLocal;
				data.region = $scope.refRegion;

				editor.addReference(data);
				break;
		}
				
	}
	$scope.editArticle = function() {
		data = {
			"title": $scope.lsTitle,
			"content": $('#redactor-content').val()
		}
		data.content = editor.editMapContent(data.content);
		data.content = editor.indexParagraph(data.content);

		switch($scope.typeCompose) {
			case 'lesson':
				data.cat= $scope.category;
				data.questions= questionList;
				data.events= eventList;
				data.timeline= $scope.timelineList;

				editor.editArticle(data, lsId);
				break;
			case 'person':
				cats = [];
				for(i in $scope.psListCat) {
					cats.push($scope.psListCat[i].id);
				}
				data.type = 'person';
				data.category = cats;
				data.image = $scope.refImage;
				data.born = $scope.psDate.born;
				data.dead = $scope.psDate.dead;
				data.region = $scope.refRegion;

				editor.editReference(data, lsId);
				break;
			case 'place':
				data.type = 'place';
				data.image = $scope.refImage;
				data.position = $scope.plLocal;
				data.region = $scope.refRegion;
				
				editor.editReference(data, lsId);
				break;
		}
	}
	$scope.viewContent = function() {
		editor.indexParagraph(str);
		xx = $('#redactor-content').val();
		xx = editor.editMapContent(xx);
		xx = xx.split('"').join('\\"');
		$('#viewContentArea').val(xx);
	}
}])

.factory('editor', ['$http', 'BASE_URL', '$q', '$filter', function($http, BASE_URL, $q, $filter) {

	function getAlert(message) {
		alert(message);
	}

	return {
		getCategories: function() {
			return $http.post(BASE_URL + 'dashboard_api/category/getcatslist').then(function(prm) {
				return prm.data;
			});
		},
		getLesson: function(id) {
			return $http.post(BASE_URL + 'dashboard_api/lesson/getLesson/' + id)
			.then(function(prm) {
				if(prm.data == null) $location.path('/lscompose');
				return prm.data;
			});
		},
		getRefPlace: function(id) {
			return $http.post(BASE_URL + 'dashboard_api/reference/getPlace/' + id)
			.then(function(prm) {
				if(prm.data == null) $location.path('/lscompose');
				console.log(prm.data);
				return prm.data;
			});
		},
		getRefPerson: function(id) {
			return $http.post(BASE_URL + 'dashboard_api/reference/getPerson/' + id)
			.then(function(prm) {
				if(prm.data == null) $location.path('/lscompose');
				console.log(prm.data);
				return prm.data;
			});
		},
		renderNew: function() {
			$('.editor-page').html('<p>Nhập nội dung vào đây</p>');
		},
		isImage: function(src) {
			var deferred = $q.defer();
			var image = new Image();
			image.onerror = function() { deferred.resolve(false); };
			image.onload = function() { deferred.resolve(true); };
			image.src = src;
			return deferred.promise;
		},
		importImg: function(url, descript) {			
			$('#redactor-content').redactor('selection.restore');

			html = '<span class="element-label">Hình ảnh: '+ descript + '</span>';
			$("#redactor-content").redactor('insert.html',html);

			par = $('#redactor-content').redactor('selection.getParent');
			$(par).addClass('image');
			$(par).prepend('<img src="'+ url +'" />');
			$(par).after('<p><br/></p>');
			$('.redactor-editor .image .element-label').next().remove();
		},		
		importVideo: function(id, el) {
			$http.post(BASE_URL + 'dashboard_api/video/getvideo/' + id).then(function(prm) {
				data = prm.data;
				if(data != "null") {
					$('#redactor-content').redactor('selection.restore');
					html = '<iframe id="'+id+'" src="//www.youtube.com/embed/'+id+'" frameborder="0" allowfullscreen></iframe>' +
						'<span class="element-label">Video: '+ data.description + '</span>';
					$("#redactor-content").redactor('insert.html',html);

					par = $('#redactor-content').redactor('selection.getParent');
					$(par).addClass('multimedia');
					$(par).after('<p><br/></p>');

					$('.redactor-editor .multimedia .element-label').next().remove();
				}
				else {
					getAlert('video không tồn tại, vui lòng tạo video trước khi chèn vào bài viết');
				}
			});			
		},	
		importReference: function(id, name, el) {
			$('#redactor-content').redactor('selection.restore');

			html = '<span>Bài liên quan: </span><a class="reference" href="#/'+id+'">'+ $filter('removeLesson')(name) +'</a>';
			$("#redactor-content").redactor('insert.html',html);

			par = $('#redactor-content').redactor('selection.getParent');
			$(par).after('<p><br/></p>');
			$('.redactor-editor .image .element-label').next().remove();
		},
		importMap: function(id, el) {
			$http.post(BASE_URL + 'dashboard_api/map/getMap/' + id).then(function(prm) {
				data = prm.data;
				console.log(data);
				if(data != "null") {
					$('#redactor-content').redactor('selection.restore');
					html = '<span class="lesson-maps" id="' + id + '">'+ id+' HistoryMap</span> ' + 
						'<span class="element-label">Bản đồ: ' + data.description + '</span>';
					$("#redactor-content").redactor('insert.html',html);

					par = $('#redactor-content').redactor('selection.getParent');
					$(par).after('<p><br/></p>');
					$(par).find('span').last().remove();
					$(par).find('span').unwrap();

					// $(el).after('<div id="' + id + '" class="lesson-maps"></div> ' + 
					// 	'<span class="element-label">Bản đồ: ' + data.description + '</span>' +
					// 	'<p><br /></p>');

				}
				else {
					// $(el).html('');
					getAlert('Bản đồ không tồn tại, vui lòng tạo bản đồ trước khi chèn vào bài viết');
				}
			});	
		},
		addVideo: function(dt) {
			return $http.get('http://gdata.youtube.com/feeds/api/videos/' + dt._id)
			.then(function(prm) {
				console.log(dt);
				return $http({
					url: BASE_URL + 'index.php/dashboard_api/video/addVideo',
					method: "POST",
					data: $.param({data: dt}),
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				});
			}).then(function(prm) {
				if(prm.data == 'video exists') {
					alert('Video đã có trong CSDL');
					return null;
				}
				else return $http.post(BASE_URL + 'index.php/dashboard_api/video/getvideos')
			}).then(function(prm) {
				if(prm) return prm.data;
				else return null;
			},
			function(err) {
				alert('You Tube Id không tồn tại');
				return null;
			});
		},
		addQuestion: function(dt) {
			return $http({
				url: BASE_URL + 'index.php/dashboard_api/question/addQuestion',
				method: "POST",
				data: $.param({data: dt}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(prm) {
				return $http.post(BASE_URL + 'index.php/dashboard_api/question/getquestions')
			}).then(function(prm) {
				return prm.data;
			})
		},
		addArticle: function(dt) {
			console.log(dt);
			$http({
				url: BASE_URL + 'index.php/dashboard_api/lesson/addLesson',
				method: "POST",
				data: $.param({data: dt}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(prm) {
				console.log(prm.data);
				alert('Thêm bài học thành công');
			})
		},
		editArticle: function(dt, id) {
			// dt._id = id;
			console.log(dt);
			$http({
				url: BASE_URL + 'index.php/dashboard_api/lesson/updateLesson',
				method: "POST",
				data: $.param({data: dt, lsId: id}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(prm) {
				console.log(prm.data);
				alert('Chỉnh sửa bài học thành công');
			})
		},
		addReference: function(dt) {
			console.log(dt);
			$http({
				url: BASE_URL + 'index.php/dashboard_api/reference/addReference',
				method: "POST",
				data: $.param({data: dt}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(prm) {
				console.log(prm.data);
				alert('Thêm bài học thành công');
			})
		},
		editReference: function(dt, id) {
			// dt._id = id;
			console.log(dt);
			$http({
				url: BASE_URL + 'index.php/dashboard_api/reference/updateReference',
				method: "POST",
				data: $.param({data: dt, lsId: id}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(prm) {
				console.log(prm.data);
				alert('Chỉnh sửa bài học thành công');
			})
		},
		sliderList: function(listId) {
			
			var $frame = $(listId);
			var $wrap  = $frame.parent();

			// Call Sly on frame
			$frame.sly({
				horizontal: 1,
				itemNav: 'centered',
				smart: 1,
				activateOn: 'click',
				mouseDragging: 1,
				touchDragging: 1,
				releaseSwing: 1,
				startAt: 1,
				scrollBar: $wrap.find('.scrollbar'),
				scrollBy: 1,
				speed: 300,
				elasticBounds: 1,
				easing: 'easeOutExpo',
				dragHandle: 1,
				dynamicHandle: 1,
				clickBar: 1,

				// Buttons
				prev: $wrap.find('.prev'),
				next: $wrap.find('.next'),
				prevPage: $wrap.find('.prevPage'),
				nextPage: $wrap.find('.nextPage')
			});

			$(listId + ' li').mousedown(function(event) {
				event.preventDefault();
				// return false;
			});
		},
		indexParagraph: function(str) {
			var content = document.createElement('div');
			$(content).html(str);
			console.log($(content).html());
			arr = [];
			$(content).find('p, table, ul, ol').each(function() {
				idx = $(this).index();
				arr.push(idx);
				$(this).attr('index', idx);
			});
			console.log($(content).html());
			return $(content).html();
		},
		editMapContent: function(content) {
			content = content.split('<span class="lesson-maps">').join('<div class="lesson-maps" id="');
			content = content.split(' HistoryMap</span>').join('">HistoryMap</div>');
			return content;
		}
	};
}])

// ===============================================================================================
.factory('videos', ['$http', 'BASE_URL', function($http, BASE_URL) {
	return {
		getVideoList: function() {
			return $http.post(BASE_URL + 'dashboard_api/video/getvideos').then(function(prm) {
				arr = [];
				angular.forEach(prm.data, function(video) {	
					arr.push(video); 
				});
				return arr;
			})
		}
	}
}])

// ===============================================================================================
.factory('reference', ['$http', 'BASE_URL', function($http, BASE_URL) {
	return {
		getReferList: function() {
			return $http.post(BASE_URL + 'dashboard_api/reference/getReferences').then(function(prm) {
				arr = [];
				angular.forEach(prm.data, function(refer) {	
					arr.push(refer); 
				});
				return arr;
			})
		},
		getArticleList: function() {
			return $http.post(BASE_URL + 'application_api/lesson/getlessonlist').then(function(prm) {
				arr = [];
				angular.forEach(prm.data, function(refer) {	
					arr.push(refer); 
				});
				return arr;
			})
		}
	}
}])

// ===============================================================================================
.factory('questions', ['$http', 'BASE_URL', function($http, BASE_URL) {
	return {
		getQuestionList: function() {
			return $http.post(BASE_URL + 'dashboard_api/question/getquestions').then(function(prm) {
				return prm.data;
			})
		},
		getQuestions: function(strArr) {
			if((typeof strArr === 'undefined') ) {
				return null;
			}
			return $http({
				url: BASE_URL + 'dashboard_api/question/getquestions',
				method: "POST",
				data: $.param({arr: strArr}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(promise) {
				return promise.data;
			})
		}
	}
}])

// ===============================================================================================
.factory('events', ['$http', 'BASE_URL', function($http, BASE_URL) {
	return {
		getEventList: function() {
			return $http.post(BASE_URL + 'dashboard_api/event/getevents').then(function(prm) {
				return prm.data;
			})
		},
		getEvents: function(strArr) {
			console.log(strArr);
			if((typeof strArr === 'undefined') ) {
				return null;
			}
			return $http({
				url: BASE_URL + 'dashboard_api/event/getevents',
				method: "POST",
				data: $.param({arr: strArr}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(promise) {
				return promise.data;
			})
		}
	}
}])

// ==============================================================================
.factory('maps', ['$http', 'BASE_URL', function($http, BASE_URL) {
	var popupMap = null;
	var timelineMap = null;
	var mapElements = [];
	var infoLast;

	var myStyle = [{"featureType":"road","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"administrative","elementType":"geometry","stylers":[{"visibility":"on"},{"weight":0.8},{"color":"#DAD5CC"}]},{"featureType":"administrative.country","elementType":"geometry.stroke","stylers":[{"weight":0.8},{"color":"#b16736"}]},{"featureType":"administrative","elementType":"labels","stylers":[{"weight":0.1},{"color":"#e1e1e1"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#f0ece6"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"transit","stylers":[{"visibility":"off"}]}];

	return {
		initialzeMap: function() {
			var mapOptions = {
				mapTypeControlOptions: {
					mapTypeIds: ['mystyle', google.maps.MapTypeId.TERRAIN]
				},
				// scrollwheel: false,
				mapTypeId: 'mystyle',
				// disableDoubleClickZoom: true,
				mapTypeControl: false,
				zoomControl: true,
				streetViewControl: false,

				center: {lat: 15.961329, lng:106.259766 },
				zoom: 4
			};
			popupMap = new google.maps.Map(document.getElementById("popup-map"),mapOptions);
			popupMap.mapTypes.set('mystyle',new google.maps.StyledMapType(myStyle,{ name:'My Style'}));
			google.maps.event.addListener(popupMap, 'click', function(event) {
				if(infoLast) infoLast.close();
			});
			google.maps.event.addDomListener(window, "resize", function() {
				google.maps.event.trigger(popupMap, "resize");
			});

			timelineMap = new google.maps.Map(document.getElementById("timeline-map"),mapOptions);
			timelineMap.mapTypes.set('mystyle',new google.maps.StyledMapType(myStyle,{ name:'My Style'}));
			google.maps.event.addListener(timelineMap, 'click', function(event) {
				if(infoLast) infoLast.close();
			});
			google.maps.event.addDomListener(window, "resize", function() {
				google.maps.event.trigger(timelineMap, "resize");
			});

			// Reload maps rendering after popup shown
			$('#importMap').on('shown.bs.modal', function(e) {
				setTimeout(function() {
					google.maps.event.trigger(popupMap, "resize");
					popupMap.panTo(new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng));
				},100)
			});
			$('#addTimeline').on('shown.bs.modal', function(e) {
				setTimeout(function() {
					google.maps.event.trigger(timelineMap, "resize");
					timelineMap.panTo(new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng));
				},100)
			});
		},
		getMapList: function() {
			return $http.post(BASE_URL + 'dashboard_api/map/getMaps').then(function(prm) {
				arr = [];
				angular.forEach(prm.data, function(map) {	
					arr.push(map); 
				});
				return arr;
			})
		},
		setPopupMap: function(mapId, num) {
			var xMap = null;
			angular.forEach(mapElements, function(el) {
				el.setMap(null);
			});

			if(num == 0) {
				xMap = popupMap;
			}
			else if(num == 1) {
				xMap = timelineMap;
			}

			google.maps.event.trigger(xMap, "resize");
			$http.post(BASE_URL + 'dashboard_api/map/getMap/' + mapId).then(function(prm) {
				data = prm.data;
				console.log(data);

				if(data.markers && data.markers.length > 0) {
					angular.forEach(data.markers, function(mkr) {
						coord = mkr.coordinate.split(",");
						point = new google.maps.LatLng(coord[1], coord[0]);

						marker = new google.maps.Marker({
							position: point,
							title: "Vị trí"
						});

						// Info Description window on click
						info = new google.maps.InfoWindow();
						content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  mkr.description +"</div>";
						
						marker.setMap(xMap);
						mapElements.push(marker);

						// Using CLOSURE Code Style
						google.maps.event.addListener(marker, 'click', (function(marker, content, info) {
							return function() {
								if(infoLast) {
									infoLast.close();
								}
								info.setContent(content);
								info.open(xMap, marker);
								infoLast = info;
							}
						})(marker, content, info));
					});
				} // End marker Process

				if(data.polygons && data.polygons.length > 0) {
					angular.forEach(data.polygons, function(poly) {
						coord = [];
						// Convert String to Array
						coor = poly.coordinate;
						coor = coor.split(' ');
						for(j in coor) {
							coor[j] = coor[j].split(',');
						}

						//Add data to $coord
						for(j in coor) {
							point = new google.maps.LatLng(coor[j][1], coor[j][0]);
							coord.push(new google.maps.LatLng(coor[j][1], coor[j][0]));
						}
						polygon = new google.maps.Polygon({
							paths: coord,
							strokeColor: poly.color,
							strokeOpacity: 0.8,
							strokeWeight: 1,
							fillColor: poly.color,
							fillOpacity: 0.35
						});

						//Get Center of Polygon
						var bounds = new google.maps.LatLngBounds();
						for(i = 0; i < coord.length; i++) {
							bounds.extend(coord[i]);
						}
						polyCenter = bounds.getCenter();

						// Info Description window on click
						info = new google.maps.InfoWindow();
						content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  poly.description +"</div>";
						
						polygon.setMap(xMap);
						mapElements.push(polygon);

						// Using CLOSURE Code Style
						google.maps.event.addListener(polygon, 'click', (function(polygon, content, info, polyCenter) {
							return function() {
								if(infoLast) {
									infoLast.close();
								}
								info.setContent(content);
								info.setPosition(polyCenter); 
								info.open(xMap);
								infoLast = info;
							}
						})(polygon, content, info, polyCenter));
					});								
				} // End Polygons Process

				if(data.polylines && data.polylines.length > 0) {
					angular.forEach(data.polylines, function(line)	{
						coord = [];
						// Convert String to Array
						coor = line.coordinate;
						coor = coor.split(' ');
						for(j in coor) {
							coor[j] = coor[j].split(',');
						}

						//Add data to $coord
						for(j in coor) {
							point = new google.maps.LatLng(coor[j][1], coor[j][0]);
							coord.push(new google.maps.LatLng(coor[j][1], coor[j][0]));
						}
						polylineConfig = {
							path: coord, strokeColor: line.color,
							strokeOpacity: 0.8, strokeWeight: 3
						}
						icons = [];
						if(line.arrow == true) {
							var arrowSymbol = {
								path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
								strokeOpacity: 1,
							};
							iconArrow = { icon: arrowSymbol, offset: "100%" };
							icons.push(iconArrow);
						}
						if(line.style == "dashed") {
							var lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 };
							dashLine = { icon: lineSymbol, offset: "0", repeat: '20px' };
							icons.push(dashLine);
							polylineConfig.strokeOpacity = 0.1;
						}
						polylineConfig.icons = icons;

						polyline = new google.maps.Polyline(polylineConfig);
						//Get Center of polyline
						var bounds = new google.maps.LatLngBounds();
						for(i = 0; i < coord.length; i++) {
							bounds.extend(coord[i]);
						}
						polyCenter = bounds.getCenter();

						// Info Description window on click
						info = new google.maps.InfoWindow();
						content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  line.description +"</div>";
						
						polyline.setMap(xMap);
						mapElements.push(polyline);

						// Using CLOSURE Code Style
						google.maps.event.addListener(polyline, 'click', (function(polyline, content, info, polyCenter) {
							return function() {
								if(infoLast) {
									infoLast.close();
								}
								info.setContent(content);
								info.setPosition(polyCenter); 
								info.open(xMap);
								infoLast = info;
							}
						})(polyline, content, info, polyCenter));
					});						
				} // End polylines Process
			});
		}
	}
}]);